Break & Retest Pro v5.1# Break & Retest Pro - Professional Trading Indicator
Transform Your Trading with Advanced Break & Retest Strategy Signals + SMA River Analysis + Automated Daily S&R
Break & Retest Pro is a comprehensive technical analysis tool designed for traders who want to identify high-probability break and retest opportunities with precision and clarity. This indicator combines sophisticated price action analysis with visual trend confirmation, advanced SMA River functionality, and automated daily support and resistance levels to help you execute proven trading strategies with confidence.
Perfect as a standalone indicator or as part of a collective trading system, Break & Retest Pro adapts to your trading style and complements other technical analysis tools seamlessly.
## 🎯 Key Features
Multi-Timeframe Break Analysis
- Advanced break point detection across multiple sensitivity levels
- Dynamic line plotting to visualize key support and resistance breaks
- Real-time identification of significant price structure violations
SMA River Analysis
- Professional SMA River system with advanced price smoothing
- Creates dynamic support and resistance channels perfect for price action river strategy
- Customizable transparency and colours for optimal chart clarity
- Visual "river" channel identifies trend flow and key price levels
Automated Daily Support & Resistance
- Optional automated daily S&R level detection and plotting
- Precise calculation of key daily support and resistance zones
- Clean, professional line display with customizable appearance
- Perfect complement to dynamic river levels for comprehensive market analysis
Visual Trading Signals
- Clear buy/sell arrow indicators for easy trade identification
- Customizable arrow display with toggle on/off functionality
- Color-coded signals that adapt to market conditions
Trend Direction Display
- Real-time trend status table showing current market direction
- Daily timeframe trend analysis for higher probability setups
- Customizable colour schemes for bullish, bearish, and neutral conditions
Professional Customization
- Adjustable line styles (Solid, Dashed, Dotted) for personal preference
- Customizable colours for all visual elements
- Clean, uncluttered chart presentation
## 📊 What You Get
Break & Retest Lines: Dynamic horizontal lines that appear when significant levels are broken, helping you identify key breakout zones and prime retest areas for high-probability entries.
SMA River System: A sophisticated moving average channel that creates a visual "river" on your charts. The river provides dynamic support and resistance levels, perfect for implementing price action river strategies. Watch for price interactions with these dynamic levels for high-probability reversal and continuation setups.
Automated Daily S&R Levels: Optional automated detection and plotting of key daily support and resistance zones. These static levels work in harmony with the dynamic river system to provide both fixed reference points and adaptive price levels for comprehensive market analysis.
Directional Arrows: Precise entry signals that appear when key levels are breached, providing clear visual cues for potential long and short opportunities. Trade these signals immediately as breakout entries, or wait for pullbacks to the broken levels for enhanced risk-to-reward ratios.
Trend Table: A compact display showing the current trend direction based on daily price action analysis, helping you align your trades with the broader market momentum.
## 🔧 Fully Customizable
- Line Appearance: Choose from multiple line styles and adjust thickness to match your charting preferences
- SMA River Settings: Customize river length, colours, transparency, and fill options
- Daily S&R Options: Toggle automated daily support and resistance on/off with customizable colours and line styles
- Colour Schemes: Customize all colours including trend display, arrows, swing point lines, river components, and daily S&R levels
- Toggle Controls: Enable or disable arrows, trend display, SMA, river components, and daily S&R independently
- Clean Interface: All settings organized in logical groups for easy configuration
## 📈 Perfect For
- Day Traders: Identify intraday break & retest setups using both dynamic river levels and automated daily S&R zones
- Swing Traders: Spot multi-day level breaks and retest opportunities enhanced by comprehensive support and resistance analysis
- Position Traders: Confirm longer-term trend direction and optimal entry points with multiple layer analysis
- Price Action Traders: Implement advanced strategies using dynamic river levels combined with static daily S&R zones
- All Experience Levels: Intuitive visual signals suitable for beginners and professionals
## 💡 Why Choose Break & Retest Pro?
This indicator eliminates the guesswork from break & retest trading by providing objective, rule-based signals based on proven price action principles. The combination of dynamic SMA River levels and optional automated daily support and resistance creates a complete multi-layered analysis system that works perfectly as a standalone indicator or integrates seamlessly with your existing trading collective.
The multiple sensitivity levels ensure you catch both minor level breaks and major trend changes, while the dual support and resistance system (dynamic river + automated daily S&R) provides continuous market reference points. The trend display keeps you aligned with the dominant market direction, creating a comprehensive trading environment.
The clean, professional presentation ensures your charts remain uncluttered while providing all the essential information needed for confident trading decisions, whether you're trading individual setups or coordinating with multiple indicators in your trading system.
## 🌊 Advanced Support & Resistance Integration
The indicator combines two powerful support and resistance methodologies:
Dynamic SMA River System:
- Advanced channel system creates powerful adaptive price levels
- Flow direction and intensity indicate trend strength
- Perfect for bounce plays and trend continuation setups
- Multi-timeframe river analysis for comprehensive market view
Automated Daily S&R Levels:
- Precise calculation and plotting of key daily support and resistance zones
- Static reference levels that complement dynamic river analysis
- Optional toggle for clean chart presentation
- Perfect for identifying major breakout and reversal zones
Combined Strategy Benefits:
- Multi-layer analysis combining adaptive and static levels
- Enhanced confluence identification when dynamic and static levels align
- Comprehensive market structure understanding
- Flexible approach suitable for all trading styles and timeframes
[i]price
Fibonacci Sequence Moving Average [BackQuant]Fibonacci Sequence Moving Average with Adaptive Oscillator
1. Overview
The Fibonacci Sequence Moving Average indicator is a two‑part trading framework that combines a custom moving average built from the famous Fibonacci number set with a fully featured oscillator, normalisation engine and divergence suite. The moving average half delivers an adaptive trend line that respects natural market rhythms, while the oscillator half translates that trend information into a bounded momentum stream that is easy to read, easy to compare across assets and rich in confluence signals. Everything from weighting logic to colour palettes can be customised, so the tool comfortably fits scalpers zooming into one‑minute candles as well as position traders running multi‑month trend following campaigns.
2. Core Calculation
Fibonacci periods – The default length array is 5, 8, 13, 21, 34. A single multiplier input lets you scale the whole family up or down without breaking the golden‑ratio spacing. For example a multiplier of 3 yields 15, 24, 39, 63, 102.
Component averages – Each period is passed through Simple Moving Average logic to produce five baseline curves (ma1 through ma5).
Weighting methods – You decide how those five values are blended:
• Equal weighting treats every curve the same.
• Linear weighting applies factors 1‑to‑5 so the slowest curve counts five times as much as the fastest.
• Exponential weighting doubles each step for a fast‑reacting yet still smooth line.
• Fibonacci weighting multiplies each curve by its own period value, honouring the spirit of ratio mathematics.
Smoothing engine – The blended average is then smoothed a second time with your choice of SMA, EMA, DEMA, TEMA, RMA, WMA or HMA. A short smoothing length keeps the result lively, while longer lengths create institution‑grade glide paths that act like dynamic support and resistance.
3. Oscillator Construction
Once the smoothed Fib MA is in place, the script generates a raw oscillator value in one of three flavours:
• Distance – Percentage distance between price and the average. Great for mean‑reversion.
• Momentum – Percentage change of the average itself. Ideal for trend acceleration studies.
• Relative – Distance divided by Average True Range for volatility‑aware scaling.
That raw series is pushed through a look‑back normaliser that rescales every reading into a fixed −100 to +100 window. The normalisation window defaults to 100 bars but can be tightened for fast markets or expanded to capture long regimes.
4. Visual Layer
The oscillator line is gradient‑coloured from deep red through sky blue into bright green, so you can spot subtle momentum shifts with peripheral vision alone. There are four horizontal guide lines: Extreme Bear at −50, Bear Threshold at −20, Bull Threshold at +20 and Extreme Bull at +50. Soft fills above and below the thresholds reinforce the zones without cluttering the chart.
The smoothed Fib MA can be plotted directly on price for immediate trend context, and each of the five component averages can be revealed for educational or research purposes. Optional bar‑painting mirrors oscillator polarity, tinting candles green when momentum is bullish and red when momentum is bearish.
5. Divergence Detection
The script automatically looks for four classes of divergences between price pivots and oscillator pivots:
Regular Bullish, signalling a possible bottom when price prints a lower low but the oscillator prints a higher low.
Hidden Bullish, often a trend‑continuation cue when price makes a higher low while the oscillator slips to a lower low.
Regular Bearish, marking potential tops when price carves a higher high yet the oscillator steps down.
Hidden Bearish, hinting at ongoing downside when price posts a lower high while the oscillator pushes to a higher high.
Each event is tagged with an ℝ or ℍ label at the oscillator pivot, colour‑coded for clarity. Look‑back distances for left and right pivots are fully adjustable so you can fine‑tune sensitivity.
6. Alerts
Five ready‑to‑use alert conditions are included:
• Bullish when the oscillator crosses above +20.
• Bearish when it crosses below −20.
• Extreme Bullish when it pops above +50.
• Extreme Bearish when it dives below −50.
• Zero Cross for momentum inflection.
Attach any of these to TradingView notifications and stay updated without staring at charts.
7. Practical Applications
Swing trading trend filter – Plot the smoothed Fib MA on daily candles and only trade in its direction. Enter on oscillator retracements to the 0 line.
Intraday reversal scouting – On short‑term charts let Distance mode highlight overshoots beyond ±40, then fade those moves back to mean.
Volatility breakout timing – Use Relative mode during earnings season or crypto news cycles to spot momentum surges that adjust for changing ATR.
Divergence confirmation – Layer the oscillator beneath price structure to validate double bottoms, double tops and head‑and‑shoulders patterns.
8. Input Summary
• Source, Fibonacci multiplier, weighting method, smoothing length and type
• Oscillator calculation mode and normalisation look‑back
• Divergence look‑back settings and signal length
• Show or hide options for every visual element
• Full colour and line width customisation
9. Best Practices
Avoid using tiny multipliers on illiquid assets where the shortest Fibonacci window may drop under three bars. In strong trends reduce divergence sensitivity or you may see false counter‑trend flags. For portfolio scanning set oscillator to Momentum mode, hide thresholds and colour bars only, which turns the indicator into a heat‑map that quickly highlights leaders and laggards.
10. Final Notes
The Fibonacci Sequence Moving Average indicator seeks to fuse the mathematical elegance of the golden ratio with modern signal‑processing techniques. It is not a standalone trading system, rather a multi‑purpose information layer that shines when combined with market structure, volume analysis and disciplined risk management. Always test parameters on historical data, be mindful of slippage and remember that past performance is never a guarantee of future results. Trade wisely and enjoy the harmony of Fibonacci mathematics in your technical toolkit.
Weighted Multi-Mode Oscillator [BackQuant]Weighted Multi‑Mode Oscillator
1. What Is It?
The Weighted Multi‑Mode Oscillator (WMMO) is a next‑generation momentum tool that turns a dynamically‑weighted moving average into a 0‑100 bounded oscillator.
It lets you decide how each bar is weighted (by volume, volatility, momentum or a hybrid blend) and how the result is normalised (Percentile, Z‑Score or Min‑Max).
The outcome is a self‑adapting gauge that delivers crystal‑clear overbought / oversold zones, divergence clues and regime shifts on any market or timeframe.
2. How It Works
• Dynamic Weight Engine
▪ Volume – emphasises bars with exceptional participation.
▪ Volatility – inverse ATR weighting filters noisy spikes.
▪ Momentum – amplifies strong directional ROC bursts.
▪ Hybrid – equal‑weight blend of the three dimensions.
• Multi‑Mode Smoothing
Choose from 8 MA types (EMA, DEMA, HMA, LINREG, TEMA, RMA, SMA, WMA) plus a secondary smoothing factor to fine‑tune lag vs. responsiveness.
• Normalization Suite
▪ Percentile – rank vs. recent history (context aware).
▪ Z‑Score – standard deviations from mean (statistical extremes).
▪ Min‑Max – scale between rolling high/low (trend friendly).
3. Reading the Oscillator
Zone Default Level Interpretation
Bull > 80 Acceleration; momentum buyers in control
Neutral 20 – 80 Consolidation / no edge
Bear < 20 Exhaustion; sellers dominate
Gradient line/area automatically shades from bright green (strong bull) to deep red (strong bear).
Optional bar‑painting colours price bars the same way for rapid chart scanning.
4. Typical Use‑Cases
Trend Confirmation – Set Weight = Hybrid, Smoothing = EMA. Enter pullbacks only when WMMO > 50 and rising.
Mean Reversion – Weight = Volatility, reduce upper / lower bands to 70 / 30 and fade extremes.
Volume Pulse – Intraday futures: Weight = Volume to catch participation surges before breakout candles.
Divergence Spotting – Compare price highs/lows to WMMO peaks for early reversal clues.
5. Inputs & Styling
Calculation: Source, MA Length, MA Type, Smoothing
Weighting: Volume period & factor, Volatility length, Momentum period
Normalisation: Method, Look‑back, Upper / Lower thresholds
Display: Gradient fills, Threshold lines, Bar‑colouring toggle, Line width & colours
All thresholds, colours and fills are fully customisable inside the settings panel.
6. Built‑In Alerts
WMMO Long – oscillator crosses up through upper threshold.
WMMO Short – oscillator crosses down through lower threshold.
Attach them once and receive push / e‑mail notifications the moment momentum flips.
7. Best Practices
Percentile mode is self‑adaptive and works well across assets; Z‑Score excels in ranges; Min‑Max shines in persistent trends.
Very short MA lengths (< 10) may produce jitter; compensate with higher “Smoothing” or longer look‑backs.
Pair WMMO with structure‑based tools (S/R, trend lines) for higher‑probability trade confluence.
Disclaimer
This script is provided for educational purposes only. It is not financial advice. Always back‑test thoroughly and manage risk before trading live capital.
Volume Momentum [BackQuant]Volume Momentum
The Volume Momentum indicator is designed to help traders identify shifts in market momentum based on volume data. By analyzing the relative volume momentum, this indicator provides insights into whether the market is gaining strength (uptrend) or losing momentum (downtrend). The strategy uses a combination of percentile-based volume normalization, weighted moving averages (WMA), and exponential moving averages (EMA) to assess volume trends.
The system focuses on the relationship between price and volume, utilizing normalized volume data to highlight key market changes. This approach allows traders to focus on volume-driven price movements, helping them to capture momentum shifts early.
Key Features
1. Volume Normalization and Percentile Calculation:
The signed volume (positive when the close is higher than the open, negative when the close is lower) is normalized against the rolling average volume. This normalized volume is then subjected to a percentile interpolation, allowing for a robust statistical measure of how the current volume compares to historical data. The percentile level is customizable, with 50 representing the median.
2. Weighted and Smoothed Moving Averages for Trend Detection:
The normalized volume is smoothed using weighted moving averages (WMA) and exponential moving averages (EMA). These smoothing techniques help eliminate noise, providing a clearer view of the underlying momentum. The WMA filters out short-term fluctuations, while the EMA ensures that the most recent data points have a higher weight, making the system more responsive to current market conditions.
3. Trend Reversal Detection:
The indicator detects momentum shifts by evaluating whether the volume momentum crosses above or below zero. A positive volume momentum indicates a potential uptrend, while a negative momentum suggests a possible downtrend. These trend reversals are identified through crossover and crossunder conditions, triggering alerts when significant changes occur.
4. Dynamic Trend Background and Bar Coloring:
The script offers customizable background coloring based on the trend direction. When volume momentum is positive, the background is colored green, indicating a bullish trend. When volume momentum is negative, the background is colored red, signaling a bearish trend. Additionally, the bars themselves can be colored based on the trend, further helping traders quickly visualize market momentum.
5. Alerts for Momentum Shifts:
The system provides real-time alerts for traders to monitor when volume momentum crosses a critical threshold (zero), signaling a trend reversal. The alerts notify traders when the market momentum turns bullish or bearish, assisting them in making timely decisions.
6. Customizable Parameters for Flexible Usage:
Users can fine-tune the behavior of the indicator by adjusting various parameters:
Volume Rolling Mean: The period used to calculate the average volume for normalization.
Percentile Interpolation Length: Defines the range over which the percentile is calculated.
Percentile Level: Determines the percentile threshold (e.g., 50 for the median).
WMA and Smoothing Periods: Control the smoothing and response time of the indicator.
7. Trend Background Visualization and Trend-Based Bar Coloring:
The background fill is shaded according to whether the volume momentum is positive or negative, providing a visual cue to indicate market strength. Additionally, bars can be color-coded to highlight the trend, making it easier to see the trend’s direction without needing to analyze numerical data manually.
8. Note on Mean-Reversion Strategy:
If you take the inverse of the signals, this indicator can be adapted for a mean-reversion strategy. Instead of following the trend, the strategy would involve buying assets that are underperforming and selling assets that are overperforming, based on volume momentum. However, it’s important to note that this approach may not work effectively on highly correlated assets, as their price movements may be too similar, reducing the effectiveness of the mean-reversion strategy.
Final Thoughts
The Volume Momentum indicator offers a comprehensive approach to analyzing volume-based momentum shifts in the market. By using volume normalization, percentile interpolation, and smoothed moving averages, this system helps identify the strength and direction of market trends. Whether used for trend-following or adapted for mean-reversion, this tool provides traders with actionable insights into the market’s volume-driven movements, improving decision-making and portfolio management.
Custom Portfolio [BackQuant]Custom Portfolio {BackQuant]
Overview
This script turns TradingView into a lightweight portfolio optimizer with institutional-grade analytics and real-time position management capabilities.
Rank up to 15 tickers every bar using a pair-wise relative-strength "league table" that compares each asset against all others through your choice of 12 technical indicators.
Auto-allocate 100% of capital to the single strongest asset and optionally apply dynamic leverage when the aggregate market is trending, with full position tracking and rebalancing logic.
Track performance against a custom buy-and-hold benchmark while watching a fully fledged stats dashboard update in real time, including 15 professional risk metrics.
How it works
Relative-strength engine – Each asset is compared against every other asset with a user-selectable indicator (default: 9/21 EMA cross). The system generates a complete comparison matrix where Asset A vs Asset B, Asset A vs Asset C, and so on, creating strength scores. The summed scores crown a weekly/daily/hourly "winner" that receives the full allocation.
Regime filter – A second indicator applied to TOTAL crypto-market cap (or any symbol you choose) classifies the environment as trending or mean-reverting . Leverage activates only in trending regimes, protecting capital during choppy or declining markets. Choose from indicators like Universal Trend Model, Relative Strength Overlay, Momentum Velocity, or Custom RSI for regime detection.
Capital & position logic – Equity grows linearly when flat and multiplicatively while invested. The system tracks entry prices, calculates returns including leverage adjustments, and handles position transitions seamlessly. Optional intra-trade leverage rebalancing keeps exposure in sync with market conditions, recalculating position sizes as regime conditions change.
Risk & performance analytics – Every confirmed bar records return, drawdown, VaR/CVaR, Sharpe, Sortino, alpha/beta vs your benchmark, gain-to-pain, Calmar, win-rate, Omega ratio, portfolio variance, skewness, and annualized statistics. All metrics render in a professional table for instant inspection with proper annualization based on your selected trading days (252 for traditional markets, 365 for crypto).
Key inputs
Backtest window – Hard-code a start date or let the script run from series' inception with full date range validation.
Asset list (15 slots) – Works with spot, futures, indices, even synthetic spreads (e.g., BYBIT:BTCUSDT.P). The script automatically cleans ticker symbols for display.
Indicator universe – Switch the comparative metric to DEMA, BBPCT, LSMAz adaptive scores, Volatility WMA, DEMA ATR, Median Supertrend, and more proprietary indicators.
With more always being added!
Leverage settings – Max leverage from 1x to any multiple, auto-rebalancing toggle, trend/reversion thresholds with precision controls.
Visual toggles – Show/hide equity curve, rolling drawdown heat-map, daily PnL spikes, position label, advanced metrics table, buy-and-hold comparison equity.
Risk-free rate input – Customize the risk-free rate for accurate Sharpe ratio calculations, supporting both percentage and decimal inputs.
On-chart visuals
Color-coded equity curve with "shadow" offset for depth perception that changes from green (profitable) to red (losing) based on recent performance momentum.
Rolling drawdown strip that fades from light to deep red as losses widen, with customizable maximum drawdown scaling for visual clarity.
Optional daily-return histogram line and zero reference for understanding day-to-day volatility patterns.
Bottom-center table prints the current winning ticker in real time with clean formatting.
Top-right metrics grid updates every bar with 15 key performance indicators formatted to three decimal places for precision.
Benchmark overlay showing buy-and-hold performance of your selected index (default: SPX) for relative performance comparison.
Typical workflow
Add the indicator on a blank chart (overlay off).
Populate ticker slots with the assets you actually trade from your broker's symbol list.
Pick your momentum or mean-reversion metric and a regime filter that matches your market hypothesis.
Set max leverage (1 = spot only) and decide if you want dynamic rebalancing.
Press the little " L " on the price axis to view the equity curve in log scale for better long-term visualization.
Enable the metrics table to monitor Sharpe, Sortino, and drawdown in real time.
Iterate through different asset combinations and indicator settings; compare performance vs buy-and-hold; refine until you find robust parameters.
Who is it for?
Systematic crypto traders looking for a one-click, cross-sectional rotation model with professional risk management.
Portfolio quants who need rapid prototyping without leaving TradingView or exporting to Python/R.
Swing traders wanting an at-a-glance health check of their multi-coin basket with instant position signals.
Fund managers requiring detailed performance attribution and risk metrics for client reporting.
Researchers backtesting momentum and mean-reversion strategies across multiple assets simultaneously.
Important notes & tips
Set Trading Days in a Year to 252 for traditional markets; 365 for 24/7 crypto to ensure accurate annualization.
CAGR and Sharpe assume the backtest start date you choose—short windows can inflate stats, so test across multiple market cycles.
Leverage is theoretical; always confirm your broker's margin rules and account for funding costs not modeled here.
The script is computationally heavy at 15 assets due to the N×N comparison matrix—reduce the list or lengthen the timeframe if you hit execution limits.
Best results often come from mixing assets with different volatility profiles rather than highly correlated instruments.
The regime filter symbol can be changed from CRYPTOCAP:TOTAL to any broad market index that represents your asset universe.
Directional Market Efficiency [QuantAlgo]🟢 Overview
The Directional Market Efficiency indicator is an advanced trend analysis tool that measures how efficiently price moves in a given direction relative to the total price movement over a specified period. Unlike traditional momentum oscillators that only measure price change magnitude, this indicator combines efficiency measurement with directional bias to provide a comprehensive view of market behavior ranging from -1 (perfectly efficient downward movement) to +1 (perfectly efficient upward movement).
The indicator transforms the classic Efficiency Ratio concept by incorporating directional bias, creating a normalized oscillator that simultaneously reveals trend strength, direction, and market regime (trending vs. ranging). This dual-purpose functionality helps traders and investors identify high-probability trend continuation opportunities while filtering out choppy, inefficient price movements that often lead to false signals and whipsaws.
🟢 How It Works
The indicator employs a sophisticated two-step calculation process that first measures pure efficiency, then applies directional weighting to create the final signal. The efficiency calculation compares the absolute net price change over a lookback period to the sum of all individual bar-to-bar price movements during that same period. This ratio reveals how much of the total price movement contributed to actual progress in a specific direction.
The directional component applies the mathematical sign of the net price change (positive for upward movement, negative for downward movement) to the efficiency ratio, creating values between -1 and +1. The resulting Directional Efficiency is then smoothed using an Exponential Moving Average to reduce noise while maintaining responsiveness. Additionally, the system incorporates a configurable threshold level that distinguishes between trending markets (high efficiency) and ranging markets (low efficiency), enabling regime-based analysis and strategy adaptation.
🟢 How to Use
1. Signal Interpretation and Market Regime Analysis
Positive Territory (Above Zero): Indicates efficient upward price movement with bullish directional bias and favorable conditions for long positions
Negative Territory (Below Zero): Signals efficient downward price movement with bearish directional bias and favorable conditions for short positions
High Absolute Values (±0.4 to ±1.0): Represent highly efficient trending conditions with strong directional conviction and reduced noise
Low Absolute Values (±0.1 to ±0.3): Suggest ranging or consolidating markets with inefficient price movement and increased whipsaw risk
Zero Line Crosses: Mark critical directional shifts and provide primary entry/exit signals for trend-following strategies
2. Threshold-Based Market Regime Classification
Above Threshold (Trending Markets): When efficiency exceeds the threshold level, markets are classified as trending, favoring momentum strategies
Below Threshold (Ranging Markets): When efficiency falls below the threshold, markets are classified as ranging, favoring mean reversion approaches
3. Preset Configurations for Different Trading Styles
Default
Universally applicable configuration optimized for medium-term analysis across multiple timeframes and asset classes, providing balanced sensitivity and noise filtering.
Scalping
Highly responsive setup for ultra-short-term trades with increased sensitivity to quick efficiency changes. Best suited for 1-15 minute charts and rapid-fire trading approaches.
Swing Trading
Designed for multi-day position holding with enhanced noise filtering and focus on sustained efficiency trends. Optimal for 1-4 hour and daily timeframe analysis.
🟢 Pro Tips for Trading and Investing
→ Trend Continuation Filter: Enter long positions when Directional Efficiency crosses above zero in trending markets (above threshold) and short positions when crossing below zero, ensuring alignment with efficient price movement.
→ Range Trading Optimization: In ranging markets (below threshold), take profits on extreme readings and enter mean reversion trades when efficiency approaches zero from either direction.
→ Multi-Timeframe Confluence: Combine higher timeframe trend direction with lower timeframe efficiency signals for optimal entry timing.
→ Risk Management Enhancement: Reduce position sizes or avoid new entries when efficiency readings are weak (near zero), as these conditions indicate higher probability of choppy, unpredictable price movement.
→ Signal Strength Assessment: Prioritize trades with high absolute efficiency values (±0.4 or higher) as these represent the most reliable directional moves with reduced likelihood of immediate reversal.
→ Regime Transition Trading: Watch for efficiency threshold breaks combined with directional changes as these often mark significant trend initiation or termination points requiring strategic position adjustments.
→ Alert Integration: Utilize the built-in alert system for real time notifications of zero-line crosses, threshold breaks, and regime changes to maintain constant market awareness without continuous chart monitoring.
utsThis custom-built indicator is designed to help traders make smarter, faster, and more confident decisions. Whether you're a scalper, swing trader, or long-term investor, this tool combines to give you a clear edge in any market.
🔑 Features:
Real-time signals for entry/exit points
Customizable settings to fit your strategy
Works on all timeframes and assets
Built-in alerts for key conditions
Clean, easy-to-read visuals
💡 Ideal For:
Identifying high-probability trade setups
Confirming trends or reversals
Reducing noise and false signals
Enhancing your current trading system
Candle close on high time frameOVERVIEW
This indicator plots persistent closing levels of higher time frame candles (H1, H4, and Daily) on the active intraday chart in real time. Unlike similar tools, it offers granular control over line projection length, fully independent toggles per timeframe, and a built-in mechanism that automatically limits the total number of historical levels to avoid chart clutter and performance issues.
CONCEPTS
Key levels from higher time frames often act as areas where price reacts or consolidates. By projecting each candle's exact closing price forward as a horizontal reference, traders can quickly identify dynamic support and resistance zones relevant to the current price action. This indicator enables seamless multi-timeframe analysis without the need to manually switch chart intervals or re-draw lines.
FEATURES
Independent Time Frame Selection: Enable or disable H1, H4, and Daily levels individually to tailor the analysis.
Custom Extension Length: Each timeframe's closing level can be projected forward for a user-defined number of bars.
Performance Optimization: The script maintains an internal limit (default: 100) on the number of active lines. When this threshold is exceeded, the oldest lines are removed automatically.
Visual Differentiation: Colors for each timeframe are fully customizable, enabling immediate recognition of level origin.
Immediate Update: New levels appear as soon as a higher timeframe candle closes, ensuring real-time reference.
USAGE
From the indicator inputs, select which timeframes you want to track.
Adjust the extension lengths to fit your trading style and time horizon.
Customize the line colors for clarity and personal preference.
Use these projected levels as part of your confluence criteria for entries, exits, or stop placement.
Combine with trend indicators or price action tools to enhance your multi-timeframe strategy.
ORIGINALITY AND ADDED VALUE
While similar scripts exist that plot higher timeframe levels, this implementation differs in:
Its efficient automatic cleanup of old lines to preserve chart performance.
The independent extension and color settings per timeframe.
Immediate reaction to new candle closes without repainting.
Simplicity of use combined with precise customization.
This combination makes it a practical and flexible tool for traders who rely on clear HTF level visualization without manual drawing or the limitations of built-in TradingView tools.
LICENSE
This script is published open-source under the Mozilla Public License 2.0.
Round Number Levels ProRound Number Levels Pro is a powerful support and resistance indicator that automatically plots psychological price levels on your chart.
What it does:
- Displays major round number levels (100, 200, 300, etc.) with prominent lines
- Shows mid-level lines (50, 150, 250, etc.) for additional reference points
- All lines extend across the entire chart for maximum visibility
- Automatically adjusts levels based on current price action
Key Features:
- Customizable Font Sizes - Large text for main levels, normal for mid-levels
- Clean Black Styling - Professional appearance that works on any chart background
- Flexible Line Styles - Choose solid, dashed, or dotted lines for main and mid levels
- Adjustable Parameters - Control number of levels, rounding increments, and label positioning
- Full Chart Extension - Lines extend both directions for complete price reference
Perfect for:
- Day traders looking for key psychological support/resistance levels
- Swing traders identifying major price zones
- Any trader who uses round numbers as decision points
How to use:
Simply add to your chart and the indicator will automatically plot relevant round number levels. Customize the settings to match your trading style and timeframe.
These psychological levels are where many traders make decisions, often creating natural support and resistance zones in the market.
Kase Convergence Divergence [BackQuant]Kase Convergence Divergence
The Kase Convergence Divergence is a sophisticated oscillator designed to measure directional market strength through the lens of volatility-adjusted log return structures. Inspired by Cynthia Kase’s work on statistical momentum and price projection ranges, this unique indicator offers a hybrid framework that merges signal processing, multi-length sweep logic, and adaptive smoothing techniques.
Unlike traditional momentum oscillators like MACD or RSI, which rely on static moving average differences, KCD introduces a dual-process system combining:
Kase-style statistical range projection (via log returns and volatility),
A sweeping loop of lookback lengths for robustness,
First and second derivative modes to capture both velocity and acceleration of price movement.
Core Logic & Computation
The KCD calculation is centered on two volatility-normalized transforms:
KSDI Up: Measures how far the current high has moved relative to a past low, normalized by return volatility.
KSDI Down: Measures how far the current low has moved relative to a past high, also normalized.
For every length in a user-defined sweep range (e.g., 25–35), both KSDI_up and KSDI_dn are computed, and their maximum values across the loop are retained. The difference between these two max values produces the raw signal:
KPO (Kase Projection Oscillator): Measures directional skew.
KCD (Kase Convergence Divergence): Defined as KPO – MA(KPO) — similar in spirit to MACD but structurally different.
Users can choose to visualize either the first derivative (KPO) , or the second derivative (KCD) , depending on market conditions or strategy style.
Key Features
✅ Multi-Length Sweep Logic: Improves signal reliability by aggregating statistical range projections across a set of lookbacks.
✅ Advanced Smoothing Modes: Supports DEMA, HMA, TEMA, LINREG, WMA and more for dynamic adaptation.
✅ Dual Derivative Modes: Choose between speed (first derivative) or smoothness (second derivative) to fit your trading regime.
✅ Color-Encoded Signal Bands: Heatmap-style oscillator coloring enhances visual feedback on trend strength.
✅ Candlestick Painting: Optional bar coloring makes it easy to spot trend shifts on the main chart.
✅ Adaptive Fill Zones: Green and red fills between the oscillator and zero line help distinguish bullish and bearish regimes at a glance.
Practical Applications
📈 Trend Confirmation: Use KCD as a secondary confirmation layer after breakout or pullback entries.
📉 Momentum Shifts: Crossover and crossunder of the zero line highlight potential regime changes.
📊 Strategy Filters: Incorporate into algos to avoid trendless or mean-reverting environments.
🧪 Derivative Switching: Flip between KPO and KCD modes depending on whether you want to measure acceleration or deceleration of price flow.
Alerts & Signals
Two built-in alerts help you catch regime shifts in real time:
Long Signal: Triggered when the selected oscillator crosses above zero.
Short Signal: Triggered when it crosses below zero.
These events can be used to generate entries, exits, or trend validation cues in multi-layer systems.
Conclusion
The Kase Convergence Divergence goes beyond traditional oscillators by offering a volatility-normalized, derivative-aware signal engine with enhanced visual dynamics. Its sweeping architecture and dynamic fill logic make it especially powerful for identifying trending environments, filtering chop, and adding statistical rigor to your trading toolkit.
Whether you’re a discretionary trader seeking precision, or a quant looking to model more robust return structures, KCD offers a creative yet analytically grounded solution.
Useful Open Price Lines - Multi-Timeframe SupportDisplay important opening price levels on your chart with this comprehensive indicator.
KEY FEATURES:
✓ Track up to 6 different opening prices simultaneously
✓ Support for intraday time-based opens (any hour:minute)
✓ Higher timeframe opens: Daily, Weekly, Monthly, Quarterly, Semi-Annual, Yearly
✓ Automatic line extension with customizable cutoff
✓ Clean chart option - hide previous day's lines
✓ Full timezone support for global markets
✓ Customizable colors, labels, and line styles
USE CASES:
- Day traders: Track key session opens (Asian, London, NY)
- Swing traders: Monitor weekly and monthly opens
- Position traders: Track quarterly and yearly opens
- Multi-timeframe analysis: See all key levels at once
CUSTOMIZATION:
- Choose any time for intraday opens (00:00 - 23:00)
- Select from multiple timeframes (D, W, M, 3M, 6M, 12M)
- Customize labels, colors, and line styles
- Adjust label offset and size
- Set line extension cutoff time
The indicator is optimized for performance and works smoothly on all timeframes.
Buy sell Trend VolumeThis indicator analyzes the flow of volume and price changes to identify potential trends.
Understanding Volume Indicator: A Comprehensive Guide
Introduction. The volume indicator is a vital tool investors and traders use to understand the liquidity and market activity in trading.
Price Deviation Table by ZonkeyXLProvides a 30 column table showing price deviation per bar close, highlighting larger deviations in red (downside) or green (upside).
Deviations that get highlighted in red/green are calculated to be 2x the amount of price movement in the previous candle, but can be customised to check any deviation size you want in the options panel.
Can be used on any timeframe but you need to specify the number of bars per table column to make it accurate to what you want.
Examples:
If used on the 1 second time frame you could specify bars to 1 and then each column value will check the price as at close on the most recent second for deviations against the close of price on the second prior, showing comparisons up to 30 seconds.
If on the 1 minute time-frame you could specify bars to 2 and then each column value would show deviations from most recent price close to 2 minutes ago, making all 30 columns show deviations for up to an hour.
At the end of the column are 3 orange coloured columns. The first one compares price to 10 bars ago. The second compares current price to 20 bars ago. The 3rd compares current price to 30 bars ago.
In our example on the 1 second above, this would mean deviation is calculated by comparing most recent close to 10 seconds ago, then to 20 seconds ago, and then to 30 seconds ago. The final 3 columns do not highlight red or green, so you can differentiate them properly from the main deviation columns at all times.
Note that the table is rolling - so once it is populated for the first time, only the final column will update while the prior values will shift one column to the left.
Gann Ultimate Time-Price Squares Method V 1.0This Script is an outcome of my Passion towards Gann Theory and his Methodology towards Trading.
The Script is still Evolving.So wait for more updates....
# Complete Trading Guide: Gann Time-Price Squares Indicator
## 🎯 Core Trading Philosophy
**Gann's Key Principle**: "When time and price come together, a change in trend occurs."
Your indicator identifies these critical moments where **Time = Price**, creating high-probability trading opportunities.
---
## 📊 Setup & Configuration
### Recommended Settings by Timeframe
| Timeframe | Pivot Lookback | Min Price Move | Tolerance | Use Case |
|-----------|---------------|----------------|-----------|----------|
| **1-5 min** | 5-8 bars | 0.5-1.0 | 1.0-2.0 | Scalping |
| **15-30 min** | 8-12 bars | 1.0-3.0 | 1.5-2.5 | Day Trading |
| **1-4 hour** | 10-15 bars | 2.0-5.0 | 2.0-3.0 | Swing Trading |
| **Daily** | 15-25 bars | 5.0-20.0 | 3.0-5.0 | Position Trading |
### Initial Setup Steps
1. **Add indicator** to your chart
2. **Set lookback period** based on your timeframe
3. **Adjust tolerance** - start with 2.0 and fine-tune
4. **Enable all visualizations** initially
5. **Position info table** where it doesn't block price action
---
## 🚀 Trading Strategies
### Strategy 1: Square Completion Reversal Trading
#### **Long Entry Setup**
```
CONDITIONS:
✅ Bullish square completes (green box appears)
✅ Info table shows "✅ COMPLETED" status
✅ Price bounces off square's bottom edge
✅ Volume increases on bounce
✅ RSI < 30 (oversold confirmation)
ENTRY: Market buy when price breaks above square's top edge
STOP: Below square's bottom edge (-2 ATR)
TARGET: Next resistance level or 1:2 Risk/Reward
```
#### **Short Entry Setup**
```
CONDITIONS:
✅ Bearish square completes (red box appears)
✅ Info table shows "✅ COMPLETED" status
✅ Price rejects square's top edge
✅ Volume increases on rejection
✅ RSI > 70 (overbought confirmation)
ENTRY: Market sell when price breaks below square's bottom edge
STOP: Above square's top edge (+2 ATR)
TARGET: Next support level or 1:2 Risk/Reward
```
### Strategy 2: Gann Angle Trend Following
#### **1x1 Angle (45°) - The Master Angle**
- **Most Important**: This is Gann's primary trend line
- **Bullish**: Price above 1x1 = uptrend intact
- **Bearish**: Price below 1x1 = downtrend intact
- **Break**: 1x1 angle break = major trend change
#### **Multi-Angle Confluence Trading**
```
STRONG BULLISH SIGNAL:
✅ Price above 1x1 angle (45°)
✅ Bouncing off 2x1 angle (support)
✅ Volume increasing
✅ Multiple angles pointing up
ENTRY: Buy on 2x1 angle bounce
STOP: Below 1x2 angle
TARGET: Next angle resistance
```
### Strategy 3: Projection Trading (Forming Squares)
#### **Anticipation Strategy**
```
SETUP IDENTIFICATION:
👀 Info table shows "⚡ FORMING" status
👀 Progress bar > 70%
👀 P/T Ratio approaching 1.00
👀 Price approaching projected completion zone
ENTRY PREPARATION:
- Set alerts for projected completion levels
- Prepare for reversal at projection zone
- Watch for volume confirmation
- Monitor momentum indicators
```
## 📈 Step-by-Step Trading Process
### Phase 1: Market Analysis (Before Trading)
1. **Check Market Trend**: Look at info table trend indicator
2. **Identify Active Pivots**: Note last significant high/low
3. **Assess Volatility**: High volatility = larger stops needed
4. **Review Completed Squares**: These become support/resistance zones
### Phase 2: Trade Setup Identification
1. **Monitor Forming Squares**: Watch progress bars in info table
2. **Check Gann Angles**: Are they supporting or opposing your bias?
3. **Confirm with Volume**: Look for volume spikes at key levels
4. **Set Alerts**: Use TradingView alerts for completion zones
### Phase 3: Trade Execution
1. **Wait for Confirmation**: Don't trade on projections alone
2. **Enter on Breakout**: Price breaking square boundaries
3. **Set Stops Immediately**: Use square edges as stop levels
4. **Scale Out**: Take partial profits at angle intersections
### Phase 4: Trade Management
1. **Trail Stops**: Use Gann angles as trailing stop levels
2. **Monitor Progress**: Watch for new square formations
3. **Exit Signals**: New squares in opposite direction
4. **Review Performance**: Analyze win/loss against square accuracy
---
## 🎯 High-Probability Setups
### Setup A: Double Confirmation
```
BULLISH EXAMPLE:
1. Bullish square completes at major support
2. Price bounces off 1x1 Gann angle
3. Volume surge confirms reversal
4. RSI divergence present
PROBABILITY: 75-80%
RISK/REWARD: 1:3 typical
```
### Setup B: Angle Breakout
```
BEARISH EXAMPLE:
1. Price breaks below 1x1 angle
2. Bearish square forming below break
3. Multiple angles now resistance
4. Volume confirms breakdown
PROBABILITY: 70-75%
RISK/REWARD: 1:2.5 typical
```
### Setup C: Time Cycle Convergence
```
REVERSAL EXAMPLE:
1. Square completion at time cycle high/low
2. Multiple Gann angles converging
3. Momentum divergence
4. Volume climax
PROBABILITY: 80-85%
RISK/REWARD: 1:4 possible
```
---
## ⚠️ Risk Management Rules
### Position Sizing
- **Conservative**: 1-2% risk per trade
- **Aggressive**: 2-3% risk per trade
- **Never exceed**: 5% total portfolio risk
### Stop Loss Guidelines
- **Completed Squares**: Opposite edge + 1 ATR
- **Gann Angles**: Below/above angle + 0.5 ATR
- **Projections**: 50% of square height
### Take Profit Targets
- **Target 1**: Next Gann angle (1:1 R/R)
- **Target 2**: Next completed square (1:2 R/R)
- **Target 3**: Major S/R level (1:3 R/R)
---
## 📊 Reading the Info Table for Trading
### Market Trend Section
```
📈 BULLISH → Look for long setups
📉 BEARISH → Look for short setups
➡️ NEUTRAL → Wait for direction
```
### Volatility Status
```
🔥 HIGH → Larger stops needed
⚡ ELEVATED → Normal stops
😴 LOW → Tighter stops possible
📊 NORMAL → Standard approach
```
### Square Progress Monitoring
```
✅ COMPLETED → Ready to trade
⚡ FORMING → Prepare for setup
🔥 ACTIVE → Monitor closely
⏳ WAITING → No immediate action
```
### P/T Ratio Interpretation
```
🎯 Perfect (0.8-1.2) → High probability setup
⚡ Good (0.6-1.4) → Moderate probability
⚠️ Watch (outside range) → Lower probability
```
---
## 🔄 Common Trading Scenarios
### Scenario 1: Trend Continuation
**Setup**: Price pulls back to completed square in uptrend
**Action**: Buy at square support with 1x1 angle confirmation
**Management**: Trail stop below each new square formation
### Scenario 2: Reversal Trading
**Setup**: Multiple squares complete at major S/R
**Action**: Fade the move when price rejects square edges
**Management**: Quick profits, tight stops
### Scenario 3: Breakout Trading
**Setup**: Price consolidates in square, then breaks out
**Action**: Trade breakout direction with volume confirmation
**Management**: Use opposite square edge as stop
---
## 📱 Alert Setup Recommendations
### Critical Alerts
1. **Square Completion**: "Gann Square Completed - Check for reversal"
2. **1x1 Angle Break**: "Master angle broken - Trend change possible"
3. **Projection Reached**: "Forming square at 90% - Prepare for reversal"
4. **Multi-Angle Touch**: "Price at angle confluence - High probability setup"
---
Remember: **Gann analysis is both art and science**. The indicator provides the mathematical framework, but successful trading requires patience, discipline, and continuous learning. Start with small positions while you master the methodology!
Enhanced Gann Time-Price SquaresEnhanced Gann Time-Price Squares Indicator
A comprehensive Pine Script indicator that identifies and visualizes W.D. Gann's time-price square formations on your charts. This tool helps traders spot potential market turning points where time and price movements align according to Gann's legendary market theories.
Key Features:
Automatic Square Detection - Identifies completed squares where price movement equals time movement
Future Projections - Shows forming squares with projected completion points
Pivot Integration - Automatically detects pivot highs/lows as square starting points
Visual Clarity - Clean box outlines with customizable colors and styles
Smart Filtering - Prevents overlapping squares and includes minimum move thresholds
Real-time Status - Information table showing current square formations
How to Use:
The indicator draws boxes when price moves from pivot points equal the time elapsed (number of bars). Green squares indicate upward movements, red squares show downward movements. Dashed lines show forming squares, while dotted lines project where they might complete.
Settings:
Adjust pivot sensitivity and minimum price moves
Customize tolerance for time-price matching
Toggle projections, labels, and visual elements
Fine-tune colors and line styles
Perfect for Gann theory practitioners and traders looking for time-based market analysis. The squares often coincide with significant support/resistance levels and potential reversal points.
Compatible with all timeframes and instruments.
More updates to follow
Momentum Regression [BackQuant]Momentum Regression
The Momentum Regression is an advanced statistical indicator built to empower quants, strategists, and technically inclined traders with a robust visual and quantitative framework for analyzing momentum effects in financial markets. Unlike traditional momentum indicators that rely on raw price movements or moving averages, this tool leverages a volatility-adjusted linear regression model (y ~ x) to uncover and validate momentum behavior over a user-defined lookback window.
Purpose & Design Philosophy
Momentum is a core anomaly in quantitative finance — an effect where assets that have performed well (or poorly) continue to do so over short to medium-term horizons. However, this effect can be noisy, regime-dependent, and sometimes spurious.
The Momentum Regression is designed as a pre-strategy analytical tool to help you filter and verify whether statistically meaningful and tradable momentum exists in a given asset. Its architecture includes:
Volatility normalization to account for differences in scale and distribution.
Regression analysis to model the relationship between past and present standardized returns.
Deviation bands to highlight overbought/oversold zones around the predicted trendline.
Statistical summary tables to assess the reliability of the detected momentum.
Core Concepts and Calculations
The model uses the following:
Independent variable (x): The volatility-adjusted return over the chosen momentum period.
Dependent variable (y): The 1-bar lagged log return, also adjusted for volatility.
A simple linear regression is performed over a large lookback window (default: 1000 bars), which reveals the slope and intercept of the momentum line. These values are then used to construct:
A predicted momentum trendline across time.
Upper and lower deviation bands , representing ±n standard deviations of the regression residuals (errors).
These visual elements help traders judge how far current returns deviate from the modeled momentum trend, similar to Bollinger Bands but derived from a regression model rather than a moving average.
Key Metrics Provided
On each update, the indicator dynamically displays:
Momentum Slope (β₁): Indicates trend direction and strength. A higher absolute value implies a stronger effect.
Intercept (β₀): The predicted return when x = 0.
Pearson’s R: Correlation coefficient between x and y.
R² (Coefficient of Determination): Indicates how well the regression line explains the variance in y.
Standard Error of Residuals: Measures dispersion around the trendline.
t-Statistic of β₁: Used to evaluate statistical significance of the momentum slope.
These statistics are presented in a top-right summary table for immediate interpretation. A bottom-right signal table also summarizes key takeaways with visual indicators.
Features and Inputs
✅ Volatility-Adjusted Momentum : Reduces distortions from noisy price spikes.
✅ Custom Lookback Control : Set the number of bars to analyze regression.
✅ Extendable Trendlines : For continuous visualization into the future.
✅ Deviation Bands : Optional ±σ multipliers to detect abnormal price action.
✅ Contextual Tables : Help determine strength, direction, and significance of momentum.
✅ Separate Pane Design : Cleanly isolates statistical momentum from price chart.
How It Helps Traders
📉 Quantitative Strategy Validation:
Use the regression results to confirm whether a momentum-based strategy is worth pursuing on a specific asset or timeframe.
🔍 Regime Detection:
Track when momentum breaks down or reverses. Slope changes, drops in R², or weak t-stats can signal regime shifts.
📊 Trade Filtering:
Avoid false positives by entering trades only when momentum is both statistically significant and directionally favorable.
📈 Backtest Preparation:
Before running costly simulations, use this tool to pre-screen assets for exploitable return structures.
When to Use It
Before building or deploying a momentum strategy : Test if momentum exists and is statistically reliable.
During market transitions : Detect early signs of fading strength or reversal.
As part of an edge-stacking framework : Combine with other filters such as volatility compression, volume surges, or macro filters.
Conclusion
The Momentum Regression indicator offers a powerful fusion of statistical analysis and visual interpretation. By combining volatility-adjusted returns with real-time linear regression modeling, it helps quantify and qualify one of the most studied and traded anomalies in finance: momentum.
Rolling Log Returns [BackQuant]Rolling Log Returns
The Rolling Log Returns indicator is a versatile tool designed to help traders, quants, and data-driven analysts evaluate the dynamics of price changes using logarithmic return analysis. Widely adopted in quantitative finance, log returns offer several mathematical and statistical advantages over simple returns, making them ideal for backtesting, portfolio optimization, volatility modeling, and risk management.
What Are Log Returns?
In quantitative finance, logarithmic returns are defined as:
ln(Pₜ / Pₜ₋₁)
or for rolling periods:
ln(Pₜ / Pₜ₋ₙ)
where P represents price and n is the rolling lookback window.
Log returns are preferred because:
They are time additive : returns over multiple periods can be summed.
They allow for easier statistical modeling , especially when assuming normally distributed returns.
They behave symmetrically for gains and losses, unlike arithmetic returns.
They normalize percentage changes, making cross-asset or cross-timeframe comparisons more consistent.
Indicator Overview
The Rolling Log Returns indicator computes log returns either on a standard (1-period) basis or using a rolling lookback period , allowing users to adapt it to short-term trading or long-term trend analysis.
It also supports a comparison series , enabling traders to compare the return structure of the main charted asset to another instrument (e.g., SPY, BTC, etc.).
Core Features
✅ Return Modes :
Normal Log Returns : Measures ln(price / price ), ideal for day-to-day return analysis.
Rolling Log Returns : Measures ln(price / price ), highlighting price drift over longer horizons.
✅ Comparison Support :
Compare log returns of the primary instrument to another symbol (like an index or ETF).
Useful for relative performance and market regime analysis .
✅ Moving Averages of Returns :
Smooth noisy return series with customizable MA types: SMA, EMA, WMA, RMA, and Linear Regression.
Applicable to both primary and comparison series.
✅ Conditional Coloring :
Returns > 0 are colored green ; returns < 0 are red .
Comparison series gets its own unique color scheme.
✅ Extreme Return Detection :
Highlight unusually large price moves using upper/lower thresholds.
Visually flags abnormal volatility events such as earnings surprises or macroeconomic shocks.
Quantitative Use Cases
🔍 Return Distribution Analysis :
Gain insight into the statistical properties of asset returns (e.g., skewness, kurtosis, tail behavior).
📉 Risk Management :
Use historical return outliers to define drawdown expectations, stress tests, or VaR simulations.
🔁 Strategy Backtesting :
Apply rolling log returns to momentum or mean-reversion models where compounding and consistent scaling matter.
📊 Market Regime Detection :
Identify periods of consistent overperformance/underperformance relative to a benchmark asset.
📈 Signal Engineering :
Incorporate return deltas, moving average crossover of returns, or threshold-based triggers into machine learning pipelines or rule-based systems.
Recommended Settings
Use Normal mode for high-frequency trading signals.
Use Rolling mode for swing or trend-following strategies.
Compare vs. a broad market index (e.g., SPY or QQQ ) to extract relative strength insights.
Set upper and lower thresholds around ±5% for spotting major volatility days.
Conclusion
The Rolling Log Returns indicator transforms raw price action into a statistically sound return series—equipping traders with a professional-grade lens into market behavior. Whether you're conducting exploratory data analysis, building factor models, or visually scanning for outliers, this indicator integrates seamlessly into a modern quant's toolbox.
Live Price Watermark (Flashing Overlay)Displays the current price as a large, centered watermark directly on your chart. The text color updates dynamically:
- Green when price rises
- Red when price falls
- Translucent black when unchanged
z-score-calkusi-v1.14z-scores incorporate the moment of N look-back bars to allow future price projection.
z-score = (X - mean)/std.deviation ; X = close
z-scores update with each new close print and with each new bar. Each new bar augments the mean and std.deviation for the N bars considered. The old Nth bar falls away from consideration with each new historical bar.
The indicator allows two other options for X: RSI or Moving Average.
NOTE: While trading use the "price" option only.
The other two options are provided for visualisation of RSI and Moving Average as z-score curves.
Use z-scores to identify tops and bottoms in the future as well as intermediate intersections through which a z-score will pass through with each new close and each new bar.
Draw lines from peaks and troughs in the past through intermediate peaks and troughs to identify projected intersections in the future. The most likely intersections are those that are formed from a line that comes from a peak in the past and another line that comes from a trough in the past. Try getting at least two lines from historical peaks and two lines from historical troughs to pass through a future intersection.
Compute the target intersection price in the future by clicking on the z-score indicator header to see a drag-able horizontal line to drag over the intersection. The target price is the last value displayed in the indicator's status bar after the closing price.
When the indicator header is clicked, a white horizontal drag-able line will appear to allow dragging the line over an intersection that has been drawn on the indicator for a future z-score projection and the associated future closing price.
With each new bar that appears, it is necessary to repeat the procedure of clicking the z-score indicator header to be able to drag the drag-able horizontal line to see the new target price for the selected intersection. The projected price will be different from the current close price providing a price arbitrage in time.
New intermediate peaks and troughs that appear require new lines be drawn from the past through the new intermediate peak to find a new intersection in the future and a new projected price. Since z-score curves are sort of cyclical in nature, it is possible to see where one has to locate a future intersection by drawing lines from past peaks and troughs.
Do not get fixated on any one projected price as the market decides which projected price will be realised. All prospective targets should be manually updated with each new bar.
When the z-score plot moves outside a channel comprised of lines that are drawn from the past, be ready to adjust to new market conditions.
z-score plots that move above the zero line indicate price action that is either rising or ranging. Similarly, z-score plots that move below the zero line indicate price action that is either falling or ranging. Be ready to adjust to new market conditions when z-scores move back and forth across the zero line.
A bar with highest absolute z-score for a cycle screams "reversal approaching" and is followed by a bar with a lower absolute z-score where close price tops and bottoms are realised. This can occur either on the next bar or a few bars later.
The indicator also displays the required N for a Normal(0,1) distribution that can be set for finer granularity for the z-score curve.This works with the Confidence Interval (CI) z-score setting. The default z-score is 1.96 for 95% CI.
Common Confidence Interval z-scores to find N for Normal(0,1) with a Margin of Error (MOE) of 1:
70% 1.036
75% 1.150
80% 1.282
85% 1.440
90% 1.645
95% 1.960
98% 2.326
99% 2.576
99.5% 2.807
99.9% 3.291
99.99% 3.891
99.999% 4.417
9-Jun-2025
Added a feature to display price projection labels at z-score levels 3, 2, 1, 0, -1, -2, 3.
This provides a range for prices available at the current time to help decide whether it is worth entering a trade. If the range of prices from say z=|2| to z=|1| is too narrow, then a trade at the current time may not be worth the risk.
Added plot for z-score moving average.
28-Jun-2025
Added Settings option for # of Std.Deviation level Price Labels to display. The default is 3. Min is 2. Max is 6.
This feature allows likelihood assessment for Fibonacci price projections from higher time frames at lower time frames. A Fibonacci price projection that falls outside |3.x| Std.Deviations is not likely.
Added Settings option for Chart Bar Count and Target Label Offset to allow placement of price labels for the standard z-score levels to the right of the window so that these are still visible in the window.
Target Label Offset allows adjustment of placement of Target Price Label in cases when the Target Price Label is either obscured by the price labels for the standard z-score levels or is too far right to be visible in the window.
Practice makes perfect.
Use this indicator at your own risk
OPR Asia-New-York [Elykia]This Pine Script indicator, called "OPR Asia-New-York ", displays time-based boxes corresponding to two specific trading periods known as OPR (Opening Price Range):
🎯 Purpose of the Indicator:
To visualize two key market time windows (morning and afternoon) as extended boxes, helping with technical analysis around opening ranges.
🕒 Two sessions displayed as boxes:
🔹 Morning OPR:
Default: from 09:00 to 09:15 (configurable)
The box extends until 10:30.
It captures the highest and lowest candle within this interval.
🔸 Afternoon OPR:
Default: from 15:30 to 15:45
The box extends until 17:30.
Follows the same logic as the morning session.
⚙️ Dashboard Options:
Enable or disable the morning or afternoon box individually
Select the timezone (e.g., GMT+2)
Customize all colors (morning/afternoon boxes, median line)
Set your own start/end/extension times for each session
📦 Each box includes:
A colored rectangle showing the price range (high/low)
A dotted median line between the high and low
The box and line extend until the end time defined
🧠 Usefulness for Traders:
Identify liquidity zones or consolidation areas
Trade setups like liquidity grabs, breakouts, or fakeouts around the OPR
Align with ICT methods or scalping strategies based on session behavior
Pristine Value Areas & MGIThe Pristine Value Areas indicator enables users to perform comprehensive technical analysis through the lens of the market profile in a fraction of the time! 🏆
A Market Profile is a charting technique devised by J. Peter Steidlmayer, a trader at the Chicago Board of Trade (CBOT), in the 1980's. He created it to gain a deeper understanding of market behavior and to analyze the auction process in financial markets. A market profile is used to analyze an auction using price, volume, and time to create a distribution-based view of trading activity. It organizes market data into a bell-curve-like structure, which reveals areas of value, balance, and imbalance.
💠 How is a Value Area Calculated?
A value area is a distribution of 68%-70% of the trading volume over a specific time interval, which represents one standard deviation above and below the point of control, which is the most highly traded level over that period.
The key reference points are as follows:
Value area low (VAL) - The lower boundary of a value area
Value area high (VAH) - The upper boundary of a value area
Point of Control (POC) - The price level at which the highest amount of a trading period's volume occurred
If we take the probability distribution of trading activity and flip it 90 degrees, the result is our Pristine Value Area!
Market Profile is our preferred method of technical analysis at Pristine Capital because it provides an objective and repeatable assessment of whether an asset is being accumulated or distributed by institutional investors. Market Profile levels work remarkably well for identifying areas of interest, because so many institutional trading algorithms have been programmed to use these levels since the 1980's!
The benefits of using Market Profile include better trade location, improved risk management, and enhanced market context. It helps traders differentiate between trending and consolidating markets, identify high-probability trade setups, and adjust their strategies based on whether the market is in balance (consolidation) or imbalance (trending). Unlike traditional indicators that rely on past price movements, Market Profile provides real-time insights into trader behavior, giving an edge to those who can interpret its nuances effectively.
Virgin Point of Control (VPOC) - A point of control from a previous time period that has not yet been revisited in subsequent periods. VPOCs are great for identifying prior supply or demand zones.
Below is a great example of price reversing lower after taking out an upside VPOC
💠 Are all POCs Created Equal?
If POCs are used to gauge supply & demand zones at key levels, then a POC with higher volume should be viewed as more significant than a POC that traded lower volume, right? We created Golden POCs as a tool to identify high volume POCs on all timeframes.
Golden POC (GPOC) - A POC that traded the highest volume compared to prior POCs (proprietary to Pristine Capital)
We calculate value areas for the following time intervals based on the user selected timeframe:
5 Minute and 15 Minute Timeframes -> Daily Value Area
The daily value area paints the distribution of the PRIOR session's trading activity. The "d" in the label references for VAHd, POCd and VALd is a visual cue that value area shown is daily.
1 Hour Timeframe -> Weekly Value Area
The weekly value area paints the distribution of the PRIOR week's trading activity. The "w" in the label references for VAHw, POCw and VALw is a visual cue that value area shown is weekly.
1 Day Timeframe -> Monthly Value Area
The monthly value area paints the distribution of the PRIOR month's trading activity. The "m" in the label references for VAHm, POCm and VALm is a visual cue that value area shown is monthly.
1 Week Timeframe -> Yearly Value Area
The yearly value area paints the distribution of the PRIOR year's trading activity. The "y" in the label references for VAHy, POCy and VALy is a visual cue that value area shown is yearly.
💠 What is a developing value area?
The developing value area provides insight into the upcoming value area while it is still forming! It appears when 80% of the way through the current value area. As the end of a trading period approaches, it can make sense to start trading off the developing value area. When the time period flips, the developing value area becomes the active value area!
💠 Value Areas Trading Setups
Two popular market profile concepts are the bullish and bearish 80% rules. The concept is that there is an 80% probability that the market will traverse the entire relevant value area.
Bullish 80% Rule - If a security opens a period below the value area low , and subsequently closes above it, the bullish 80% rule triggers, turning the value area green. One can trade for a move to the top of the value area, using a close below the value area low as a potential stop!
In the below example, HOOD triggered the bullish 80% rule after it reclaimed the monthly value area!
HOOD proceeded to rally through the monthly value area and beyond in subsequent trading sessions. Finding the first stocks to trigger the bullish 80% rule after a market correction is key for spotting the next market leaders!
Bearish 80% Rule - If a security opens a period above the value area high , and subsequently closes below it, the bearish 80% rule triggers, turning the value area red. One can trade for a move to the bottom of the value area, using a close above the value area high as a potential stop!
ES proceeded to follow through and test the value area low before trending below the weekly value area
Value Area Breakouts - When a security is inside of value, the auction is in balance. When it breaks out from a value area, it could be entering a period of price discovery. One can trade these breaks out of value with tight risk control by setting a stop inside the value area! These breakouts can be traded on all chart timeframes depending on the timeframe of the individual trader. Combining multiple timeframes can result in even more effective trading setups.
RBLX broke out from the monthly value area on 4/22/25👇
RBLX proceeded to rally +62.78% in 39 trading sessions following the monthly VAH breakout!
💠 Market Generated Information to Improve Your Situational Awareness!
In addition to the value areas, we've also included stat tables with useful market generated information. The stats displayed vary based on the timeframe the user has up on their screen. This incentivizes traders to check the chart on multiple timeframes before taking a trade!
Metrics Grouped By Use Case
Performance
▪ YTD α - YTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a year-to-date basis.
▪ MTD α - MTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a month-to-date basis.
▪ WTD α - WTD Alpha (α) measures the risk-adjusted, excess return of a security over its user defined benchmark, on a week-to-date basis.
▪ YTD %Δ - Year-to-date percent change in price
▪ MTD %Δ - Month-to-date percent change in price
▪ WTD %Δ - Week-to-date percent change in price
Volatility
▪ ATR % - The Average True Range (ATR) expressed as a percentage of an asset's price.
▪ Beta - Measures the price volatility of a security compared to the S&P 500 over the prior 5 years (since inception if 5 years of data is not available)
Risk Analysis
▪ LODx - Low-of-day extension - ATR % multiple from the low of day (measures how extended a stock is from its low of day)
▪ MAx - Moving average extension - ATR % multiple from the user-defined moving average (measures how extended a security is from its moving average). Default moving average = 50D SMA
Why does MAx matter?
MAx measures the number of ATR % multiples a security is trading away from a key moving average. The default moving average length is 50 days.
MAx can be used to identify mean reversion trades . When a security trends strongly in one direction and moves significantly above or below its moving average, the price often tends to revert back toward the average.
Example, if the ATR % of the security is 5%, and the stock is trading 50% higher than the 50D SMA, the MAx would be 50%/5% = 10. A user might opt to take a countertrend trade when the MAx exceeds a predetermined level.
The MAx can also be useful when trading breakouts above or below the key moving average of your choosing. The lower the MAx, the tighter stop loss one can take if trading against that level.
Identifying an extreme price extension using MAx 👇
Price mean reverted immediately following the high MAx 👇
💠 Trend Analysis
The Trend Analysis section consists of short-term and long-term stage analysis data as well as the value area timeframe and price in relation to the value area.
Stage Analysis
▪ ST ⇅ - Short-term stage analysis indicator
▪ LT ⇅ - Long-term stage analysis indicator
Short-term and long-term stage analysis data is provided in the two rightmost columns of each table. The columns are labeled ST ⇅ and LT ⇅.
Why is Stage Analysis important? Popularized by Stan Weinstein, stage analysis is a trend following system that classifies assets into four stages based on price-trend analysis.
The problem? The interpretation of stage analysis is highly subjective. Based on the methodology provided in Stan Weinstein’s books, five different traders could look at the same chart, and come to different conclusions as to which stage the security is in!
We solved for this by creating our own methodology for classifying stocks into stages using moving averages. This indicator automates that analysis, and produces short-term and long-term trend signals based on user-defined key moving averages. You won’t find this in any textbook or course, because it’s completely unique to the Pristine trading methodology.
Our indicator calculates a short-term trend signal using two moving averages; a fast moving average, and a slow moving average. We default to the 10D EMA as the fast moving average & the 20D SMA as the slow moving average. A trend signal is generated based on where price is currently trading with respect to the fast moving average and the slow moving average. We use the signal to guide shorter-term swing trades.
In general, we want to take long trades in stocks with strengthening trends, and short trades in stocks with weakening trends. The user is free to change the moving averages based on their own short-term timeframe. Every trader is unique!
The same process is applied to calculate the long-term trend signal. We default to the 50D SMA as our fast moving average, and the 200D SMA as the slow moving average for the LT ⇅ signal calculation, but users can change these to fit their own unique trading style.
What is Stage 1?
Stage 1 identifies stocks that transitioned from downtrends, into bottoming bases.
Stage 1A - Bottom Signal: Marks the first day a security shows initial signs of recovery after a downtrend, with early indications of strength emerging.👇
Stage 1B - Bottoming Process: Identifies the ongoing phase where the security continues to stabilize and strengthen, confirming the base-building process after the initial signal.👇
Stage 1R - Failed Uptrend: Detects when a security that had entered an early uptrend loses momentum and slips back into a bottoming phase, signaling a failed breakout.👇
What is Stage 2?
Stage 2 identifies stocks that transitioned from bottoming bases to uptrends.
Stage 2A - Breakout: Marks the first day a security decisively breaks out, signaling the start of a new uptrend.👇
Stage 2B - Uptrend: Identifies when the security continues to trade in an established uptrend following the initial breakout, with momentum building but not yet showing full strength.👇
Stage 2C - Strong Uptrend: Detects when the uptrend strengthens further, with the security displaying clear signs of accelerating strength and buying pressure.👇
Stage 2R - Failed Breakdown: Detects when a security that had recently entered a corrective phase reverses course and reclaims its upward trajectory, moving back into an uptrend.👇
What is Stage 3?
Stage 3 identifies stocks that transitioned from uptrends to topping bases.
Stage 3A - Top Signal: Marks the first day a security shows initial signs of weakness after an uptrend, indicating the start of a potential topping phase.👇
Stage 3B - Topping Process: Identifies the period following the initial signal when the security continues to show signs of distribution and potential trend exhaustion.👇
Stage 3R - Failed Breakdown: Detects when a security that had entered a deeper corrective phase reverses upward, recovering enough strength to re-enter the topping phase.👇
What is Stage 4?
Stage 4 identifies stocks that transitioned from topping bases to downtrends.
Stage 4A - Breakdown: Marks the first day a security decisively breaks below key support levels, signaling the start of a new downward trend.👇
Stage 4B - Downtrend: Identifies when the security continues to trend lower following the initial breakdown, with sustained bearish momentum, though not yet fully entrenched.👇
Stage 4C - Strong Downtrend: Detects when the downtrend intensifies, with the security displaying clear signs of accelerating weakness and selling pressure.👇
Stage 4R - Failed Bottom: Detects when a security that had begun to show early signs of bottoming reverses course and resumes its decline, falling back into a downtrend.👇
Stage N/A - Recent IPO: Applies to stocks that recently IPO’ed and don’t have enough data to calculate all necessary moving averages.
Value Area
In Trend Analysis, the value area information is helpful to gauge price in relation to the value area.
▪ VA(y) - Categorizes the security based on the relation of price to the yearly value area
▪ VA(m) - Categorizes the security based on the relation of price to the monthly value area
▪ VA(w) - Categorizes the security based on the relation of price to the weekly value area
Value area states:
▪ ABOVE = Price above the value area high
▪ BELOW = Price below the value area low
▪ INSIDE = Price inside the value area
▪ Bull 80% = Bullish 80% rule in effect
▪ Bear 80% rule = Bearish 80% rule in effect
For example, in the chart above, VA(m) - ABOVE indicates a monthly value area and price is above the VAH.
💠 What Makes This Indicator Unique
There are many value area indicators, however...
Value Area
▪ Golden POC (GPOC) - This is a proprietary concept.
▪ Unique Label Customization
Pristine value areas often comprehensive and unique label customizations. Styles include options to display any combination of the following on your labels:
• Price levels associated with market profile levels
• % distance of market profile levels from security price
• ATR% extension of market profile levels from security price
Multi-Timeframe Analysis
Based on the chart timeframe, unique market generated information is shown to facilitate multi-timeframe analysis.
▪ Weekly Timeframe
On the weekly timeframe the focus is the bigger picture and the metrics reflect this perspective. Performance data includes YTD Alpha and YTD percent change in price. Volatility is measured using ATR % and the industry standard beta. Trend analysis for this higher timeframe include the 52-week range, which measures where a security is trading in relation to its 52wk high and 52wk low. Also included is the where price is in relation to yearly value area.
▪ Daily Timeframe
As one drills down to the daily timeframe, the performance metrics include MTD alpha and MTD percent change in price.
Risk analysis includes the low-of-day extension (LODx), which is the ATR % multiple from the low of the day, to measures how extended a stock is from its low of day. In addition, the moving average extension (MAx) is the ATR % multiple from the user-defined moving average, measures how extended a security is from its
moving average. The default moving average is the 50D SMA, however this can be customized in Settings.
Trend Analysis on the daily timeframe includes the Pristine Capital methodology for classifying stocks into stages using moving averages. Both short-term and long-term stage analysis data is included. Finally, price in relation to monthly value area is shown.
▪ Hourly Timeframe
An the hourly timeframe, performance metrics include WTD alpha and WTD percent change in price. Trend analysis includes the daily closing range (DCR) and price in relation to weekly value area.
💠 Settings and Preferences
💠 Acknowledgements
We'd like to thank @dgtrd, a TradingView Pine Wizard, for his insight on the finer details when working with volume profiles.
Calc win-LoserHow to Use the Calc win-Loser Indicator
The indicator calculates the profit or loss of the operation, showing how much you gained or lost on the invested amount, without adding the initial capital, displaying only the profit or loss separately.
Use a period (.) to separate decimal numbers, without thousand separators (e.g., 1000 for one thousand, 1000.50 for one thousand and fifty cents).
Price Definition for Calculation
Long Position (buy):
Low Price: entry price (lower)
High Price: exit price (higher)
Example: enter at 1 and exit at 3
Short Position (sell):
High Price: entry price (higher)
Low Price: exit price (lower)
Example: enter at 3 and exit at 1
Main Parameters
Parameter Description Example
Low Price Base price for calculation (Long: entry; Short: exit) 1
High Price Base price for calculation (Long: exit; Short: entry) 3
Leverage Operation multiplier (leverage) 2.0
Universal Amount Total amount invested 1000
Broker Fee (%) Percentage fee charged by broker 0.1
Currency Currency symbol for value display USD
Practical Example
Long: entry at 1, exit at 3, 2x leverage, $1000 investment, 0.1% fee.
Short: entry at 3, exit at 1, 2x leverage, $1000 investment, 0.1% fee.
The indicator will show the expected profit or loss based on the percentage difference adjusted by leverage and subtracting the broker fee.
Notes
Adjust prices according to the type of operation (Long or Short).
Use a period for decimals and do not use thousand separators.
This indicator is a simulation tool and does not execute automatic trades.
Original indicator by Canhoto-Medium — protected to maintain order and respect, prevent copying and plagiarism.
Bilateral Filter For Loop [BackQuant]Bilateral Filter For Loop
The Bilateral Filter For Loop is an advanced technical indicator designed to filter out market noise and smooth out price data, thus improving the identification of underlying market trends. It employs a bilateral filter, which is a sophisticated non-linear filter commonly used in image processing and price time series analysis. By considering both spatial and range differences between price points, this filter is highly effective at preserving significant trends while reducing random fluctuations, ultimately making it suitable for dynamic trend-following strategies.
Please take the time to read the following:
Key Features
1. Bilateral Filter Calculation:
The bilateral filter is the core of this indicator and works by applying a weight to each data point based on two factors: spatial distance and price range difference. This dual weighting process allows the filter to preserve important price movements while reducing the impact of less relevant fluctuations. The filter uses two primary parameters:
Spatial Sigma (σ_d): This parameter adjusts the weight applied based on the distance of each price point from the current price. A larger spatial sigma means more smoothing, as further away values will contribute more heavily to the result.
Range Sigma (σ_r): This parameter controls how much weight is applied based on the difference in price values. Larger price differences result in smaller weights, while similar price values result in larger weights, thereby preserving the trend while filtering out noise.
The output of this filter is a smoothed version of the original price series, which eliminates short-term fluctuations, helping traders focus on longer-term trends. The bilateral filter is applied over a rolling window, adjusting the level of smoothing dynamically based on both the distance between values and their relative price movements.
2. For Loop Calculation for Trend Scoring:
A for-loop is used to calculate the trend score based on the filtered price data. The loop compares the current value to previous values within the specified window, scoring the trend as follows:
+1 for upward movement (when the filtered value is greater than the previous value).
-1 for downward movement (when the filtered value is less than the previous value).
The cumulative result of this loop gives a continuous trend score, which serves as a directional indicator for the market's momentum. By summing the scores over the window period, the loop provides an aggregate value that reflects the overall trend strength. This score helps determine whether the market is experiencing a strong uptrend, downtrend, or sideways movement.
3. Long and Short Conditions:
Once the trend score has been calculated, it is compared against predefined threshold levels:
A long signal is generated when the trend score exceeds the upper threshold, indicating that the market is in a strong uptrend.
A short signal is generated when the trend score crosses below the lower threshold, signaling a potential downtrend or trend reversal.
These conditions provide clear signals for potential entry points, and the color-coding helps traders quickly identify market direction:
Long signals are displayed in green.
Short signals are displayed in red.
These signals are designed to provide high-confidence entries for trend-following strategies, helping traders capture profitable movements in the market.
4. Trend Background and Bar Coloring:
The script offers customizable visual settings to enhance the clarity of the trend signals. Traders can choose to:
Color the bars based on the trend direction: Bars are colored green for long signals and red for short signals.
Change the background color to provide additional context: The background will be shaded green for a bullish trend and red for a bearish trend. This visual feedback helps traders to stay aligned with the prevailing market sentiment.
These features offer a quick visual reference for understanding the market's direction, making it easier for traders to identify when to enter or exit positions.
5. Threshold Lines for Visual Feedback:
Threshold lines are plotted on the chart to represent the predefined long and short levels. These lines act as clear markers for when the market reaches a critical threshold, triggering a potential buy (long) or sell (short) signal. By showing these threshold lines on the chart, traders can quickly gauge the strength of the market and assess whether the trend is strong enough to warrant action.
These thresholds can be adjusted based on the trader's preferences, allowing them to fine-tune the indicator for different market conditions or asset behaviors.
6. Customizable Parameters for Flexibility:
The indicator offers several parameters that can be adjusted to suit individual trading preferences:
Window Period (Bilateral Filter): The window size determines how many past price values are used to calculate the bilateral filter. A larger window increases smoothing, while a smaller window results in more responsive, but noisier, data.
Spatial Sigma (σ_d) and Range Sigma (σ_r): These values control how sensitive the filter is to price changes and the distance between data points. Fine-tuning these parameters allows traders to adjust the degree of noise reduction applied to the price series.
Threshold Levels: The upper and lower thresholds determine when the trend score crosses into long or short territory. These levels can be customized to better match the trader's risk tolerance or asset characteristics.
Visual Settings: Traders can customize the appearance of the chart, including the line width of trend signals, bar colors, and background shading, to make the indicator more readable and aligned with their charting style.
7. Alerts for Trend Reversals:
The indicator includes alert conditions for real-time notifications when the market crosses the defined thresholds. Traders can set alerts to be notified when:
The trend score crosses the long threshold, signaling an uptrend.
The trend score crosses the short threshold, signaling a downtrend.
These alerts provide timely information, allowing traders to take immediate action when the market shows a significant change in direction.
Final Thoughts
The Bilateral Filter For Loop indicator is a robust tool for trend-following traders who wish to reduce market noise and focus on the underlying trend. By applying the bilateral filter and calculating trend scores, this indicator helps traders identify strong uptrends and downtrends, providing reliable entry signals with minimal market noise. The customizable parameters, visual feedback, and alerting system make it a versatile tool for traders seeking to improve their timing and capture profitable market movements.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future.
INDEX:BTCUSD
INDEX:ETHUSD
CRYPTO:SOLUSD
Wavelet Filter with Adaptive Upsampling [BackQuant]Wavelet Filter with Adaptive Upsampling
The Wavelet Filter with Adaptive Upsampling is an advanced filtering and signal reconstruction tool designed to enhance the analysis of financial time series data. It combines wavelet transforms with adaptive upsampling techniques to filter and reconstruct price data, making it ideal for capturing subtle market movements and enhancing trend detection. This system uses high-pass and low-pass filters to decompose the price series into different frequency components, applying adaptive thresholding to eliminate noise and preserve relevant signal information.
Shout out to Loxx for the Least Squares fitting of trigonometric series and Quinn and Fernandes algorithm for finding frequency
www.tradingview.com
Key Features
1. Frequency Decomposition with High-Pass and Low-Pass Filters:
The indicator decomposes the input time series using high-pass and low-pass filters to separate the high-frequency (detail) and low-frequency (trend) components of the data. This decomposition allows for a more accurate analysis of underlying trends, while mitigating the impact of noise.
2. Soft Thresholding for Noise Reduction:
A soft thresholding function is applied to the high-frequency component, allowing for the reduction of noise while retaining significant market signals. This function adjusts the coefficients of the high-frequency data, removing small fluctuations and leaving only the essential price movements.
3. Adaptive Upsampling Process:
The upsampling process in this script can be customized using different methods: sinusoidal upsampling, advanced upsampling, and simple upsampling. Each method serves a unique purpose:
Sinusoidal Upsample uses a sine wave to interpolate between data points, providing a smooth transition.
Advanced Upsample utilizes a Quinn-Fernandes algorithm to estimate frequency and apply more sophisticated interpolation techniques, adapting to the market’s cyclical behavior.
Simple Upsample linearly interpolates between data points, providing a basic upsampling technique for less complex analysis.
4. Reconstruction of Filtered Signal:
The indicator reconstructs the filtered signal by summing the high and low-frequency components after upsampling. This allows for a detailed yet smooth representation of the original time series, which can be used for analyzing underlying trends in the market.
5. Visualization of Reconstructed Data:
The reconstructed series is plotted, showing how the upsampling and filtering process enhances the clarity of the price movements. Additionally, the script provides the option to visualize the log returns of the reconstructed series as a histogram, with positive returns shown in green and negative returns in red.
6. Cumulative Series and Trend Detection:
A cumulative series is plotted to visualize the compounded effect of the filtered and reconstructed data. This feature helps traders track the overall performance of the asset over time, identifying whether the asset is following a sustained upward or downward trend.
7. Adaptive Thresholding and Noise Estimation:
The system estimates the noise level in the high-frequency component and applies an adaptive thresholding process based on the standard deviation of the downsampled data. This ensures that only significant price movements are retained, further refining the trend analysis.
8. Customizable Parameters for Flexibility:
Users can customize the following parameters to adjust the behavior of the indicator:
Frequency and Phase Shift: Control the periodicity of the wavelet transformation and the phase of the upsampling function.
Upsample Factor: Adjust the level of interpolation applied during the upsampling process.
Smoothing Period: Determine the length of time used to smooth the signal, helping to filter out short-term fluctuations.
References
Enhancing Cross-Sectional Currency Strategies with Context-Aware Learning to Rank
arxiv.org
Daubechies Wavelet - Wikipedia
en.wikipedia.org
Quinn Fernandes Fourier Transform of Filtered Price by Loxx
Note on Usage for Mean-Reversion Strategy
This indicator is primarily designed for trend-following strategies. However, by taking the inverse of the signals, it can be adapted for mean-reversion strategies. This involves buying underperforming assets and selling outperforming ones. Caution: This method may not work effectively with highly correlated assets, as the price movements between correlated assets tend to mirror each other, limiting the effectiveness of mean-reversion strategies.
Final Thoughts
The Wavelet Filter with Adaptive Upsampling is a powerful tool for traders seeking to improve their understanding of market trends and noise. By using advanced wavelet decomposition and adaptive upsampling, this system offers a clearer, more refined picture of price movements, enhancing trend-following strategies. It’s particularly useful for detecting subtle shifts in market momentum and reconstructing price data in a way that removes noise, providing more accurate insights into market conditions.